import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { ClassMajorTreeService, NewInfos } from './class-major-tree.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { StatusEnum } from '../../../core/enum/status.enum';
import { NzMessageService } from 'ng-zorro-antd';
import { StorageUtil } from '../../../utils/storage.util';

declare var $: any;

@Component({
  selector: 'app-class-major-tree',
  templateUrl: './class-major-tree.component.html',
  providers: [ClassMajorTreeService]
})
/**
 * @author zhouxin
 * @date 2019-04-20
 * @description 班级树
 */
export class ClassMajorTreeComponent implements OnInit {

  @Output() classTreeClick: EventEmitter<any> = new EventEmitter();
  @Input() treeId: string; // 树id;
  @Input() isEdit: boolean; // 树是否可编辑，true：是，false:否
  treeAddOrUpdate = true; // 新增 /重命名分类
  isVisible = false;
  roleManager = 1;
  validateForm: FormGroup;
  // 新增学院专业类
  newInfos: NewInfos = new NewInfos();
  // tree nodes
  treeNodes = [];
  // 分类树设置
  setting = {
    data: {
      key: {
        name: 'name',
        children: 'childrenList'
      },
      simpleData: {
        enable: true,
        idKey: 'id'
      },
      keep: {
        parent: true,
        leaf: true
      }
    },
    callback: {
      onClick: (event, treeId, treeNode) => {
        this.classTreeClick.emit({
          id: treeNode.id,
          name: treeNode.name,
          pId: treeNode.parentId,
          type: treeNode.type
        });
      },
      onRename: (event, treeId, treeNode) => {
        if (this.treeAddOrUpdate) {
          this.classMajorTreeService.addNewNode({name: treeNode.name, parentId: treeNode.parentId}).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
              this.message.success(res.message);
              this.resetTree();
            }
          });
        } else {
          this.classMajorTreeService.editNode({
            id: treeNode.id,
            name: treeNode.name,
            parentId: treeNode.parentId
          }).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
              this.message.success(res.message);
              this.resetTree();
            }
          });
        }
      }
    },
    view: {
      showIcon: false,
      addHoverDom: (treeId, treeNode) => {
        if (!this.isEdit) {
          return;
        }
        const aObj = $('#' + treeNode.tId + '_a');
        if ($('#' + treeNode.id + '_edit').length > 0) {
          return;
        }
        if (this.roleManager !== 1) { return; }
        if (treeNode.type === '部门') {
          // 只能添加
          if (aObj.children('.btn-op').length === 0) {
            aObj.append('<span class="button btn-op add" id="' + treeNode.id + '_add" title="新增"></span>');
          }
        } else if (treeNode.type === '专业') {
          // 只能修改和删除
         aObj.append('<span class="button btn-op edit" id="' + treeNode.id + '_edit" title="重命名"></span>'
           + '<span class="button btn-op remove" id="' + treeNode.id + '_remove" title="删除"></span>');
        }
        const edit = $('#' + treeNode.id + '_edit');
        const remove = $('#' + treeNode.id + '_remove');
        const add = $('#' + treeNode.id + '_add');
        const zTree = $.fn.zTree.getZTreeObj(this.treeId);
        if (edit) {
          edit.bind('click', () => {
            this.treeAddOrUpdate = false; // 编辑
            if (treeNode) {
              zTree.editName(treeNode);
            }
          });
        }

        if (add) {
          add.bind('click', () => {
            treeNode.isParent = true;
            this.newInfos = new NewInfos();
            this.newInfos.parentId = treeNode.id;
            if (treeNode.value === '0') {
              // 如果点击的当前节点是学院，那么下面只能是专业
              this.newInfos.type = '1';
            } else {
              // 点击了专业的新增，只能是新增专业
              this.newInfos.type = '1';
            }
            this.initForm();
            this.isVisible = true;
          });
        }
        if (remove) {
          remove.bind('click', () => {
            this.classMajorTreeService.deleteNode({id: treeNode.id}).subscribe(res => {
              if (res.status === StatusEnum.SUCCESS) {
                this.message.success(res.message);
                this.resetTree();
              }
            });
          });
        }
      },
      removeHoverDom: (treeId, treeNode) => {
        $('#' + treeNode.id + '_edit').remove();
        $('#' + treeNode.id + '_remove').remove();
        $('#' + treeNode.id + '_add').remove();
        $('.btn-op').remove();
      }
    }
  };

  constructor(private classMajorTreeService: ClassMajorTreeService,
              private message: NzMessageService,
              private fb: FormBuilder) {
  }

  ngOnInit() {
    setTimeout(() => {
      this.resetTree();
    }, 100);
    this.initForm();
    // this.roleManager = StorageUtil.getLocalStorage('roleManager');
  }

  getDeptAndMajor() {
  }

  /**
   * 校验
   */
  initForm() {
    this.validateForm = this.fb.group({
      parentId: [this.newInfos.parentId, []],
      name: [this.newInfos.name, [Validators.required]],
      type: [this.newInfos.type, [Validators.required]]
    });
  }

  /**
   * 获取学院专业树
   */
  resetTree() {
    this.classMajorTreeService.getDeptAndMajorApi({}).subscribe(data => {
      if (data.status === StatusEnum.SUCCESS) {
        this.treeNodes = data.datas;
        $.fn.zTree.init($('#' + this.treeId), this.setting, data.datas);
        if (this.treeNodes.length) {
          $('#mainTree_1_a').click();
          // 直接抛出第一节点的数据
          const treeNode = this.treeNodes[0];
          this.classTreeClick.emit({
            id: treeNode.id,
            name: treeNode.name,
            pId: treeNode.parentId,
            type: treeNode.type
          });
        }
      }
    });
  }

  /**
   * 新增根分类
   */
  addRoot() {
    this.newInfos = new NewInfos();
    this.isVisible = true;
    this.newInfos.type = '0';
    this.initForm();
  }

  /**
   * 新增顶级分类保存保存
   */
  submit() {
    if (!this.newInfos.parentId) {
      this.newInfos.parentId = '0';
    }
    this.classMajorTreeService.addNewNode(this.newInfos).subscribe(data => {
      if (data.status === StatusEnum.SUCCESS) {
        this.isVisible = false;
        this.resetTree();
      }
    });
  }
}
